<template>
  <div class="app-container">
    <!-- 头部操作区 -->
    <ContentWrap>
      <div class="flex justify-between">
        <div>
          <h2>Look-IM 系统配置</h2>
          <p class="text-gray-500">管理Look-IM即时通讯系统的各项配置参数</p>
        </div>
        <div class="space-x-2">
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            <Icon icon="ep:check" class="mr-1" />
            保存配置
          </el-button>
          <el-button type="warning" @click="handleReset" :loading="resetLoading">
            <Icon icon="ep:refresh" class="mr-1" />
            重置默认
          </el-button>
          <el-button @click="handleRefresh" :loading="loading">
            <Icon icon="ep:refresh" class="mr-1" />
            刷新
          </el-button>
        </div>
      </div>
    </ContentWrap>

    <!-- 配置表单 -->
    <ContentWrap>
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 系统信息配置 -->
        <el-tab-pane label="系统信息" name="sysInfo">
          <el-form ref="sysInfoFormRef" :model="formData.sysInfo" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="系统名称" prop="name">
                  <el-input v-model="formData.sysInfo.name" placeholder="请输入系统名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="系统Logo" prop="logo">
                  <UploadImg
                    v-model="formData.sysInfo.logo"
                    :file-size="2"
                    :file-type="['image/jpeg', 'image/png', 'image/gif']"
                    width="120px"
                    height="80px"
                    borderradius="8px"
                    class="upload-logo"
                  />
                  <div class="text-xs text-gray-400 mt-1">
                    支持 jpg、png、gif 格式，建议尺寸 120x80，大小不超过 2MB
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="系统状态" prop="state">
                  <el-radio-group v-model="formData.sysInfo.state">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册认证" prop="regauth">
                  <el-radio-group v-model="formData.sysInfo.regauth">
                    <el-radio label="1">需要认证</el-radio>
                    <el-radio label="0">无需认证</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="注册类型" prop="regtype">
                  <el-select v-model="formData.sysInfo.regtype" class="w-full">
                    <el-option label="手机号注册" value="1" />
                    <el-option label="邮箱注册" value="2" />
                    <el-option label="手机号或邮箱" value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运行模式" prop="runMode">
                  <el-radio-group v-model="formData.sysInfo.runMode">
                    <el-radio label="1">正常模式</el-radio>
                    <el-radio label="0">维护模式</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="IP归属地" prop="ipregion">
                  <el-radio-group v-model="formData.sysInfo.ipregion">
                    <el-radio label="1">显示</el-radio>
                    <el-radio label="0">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册间隔(秒)" prop="registerInterval">
                  <el-input-number v-model="formData.sysInfo.registerInterval" :min="60" class="w-full" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="系统描述" prop="description">
              <el-input
                v-model="formData.sysInfo.description"
                type="textarea"
                :rows="3"
                placeholder="请输入系统描述"
              />
            </el-form-item>
            <el-form-item label="关闭提示" prop="closeTips">
              <el-input
                v-model="formData.sysInfo.closeTips"
                type="textarea"
                :rows="2"
                placeholder="系统关闭时显示的提示信息"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 聊天配置 -->
        <el-tab-pane label="聊天配置" name="chatInfo">
          <el-form ref="chatInfoFormRef" :model="formData.chatInfo" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="在线状态" prop="online">
                  <el-radio-group v-model="formData.chatInfo.online">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="WebRTC" prop="webrtc">
                  <el-radio-group v-model="formData.chatInfo.webrtc">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="群聊功能" prop="groupChat">
                  <el-radio-group v-model="formData.chatInfo.groupChat">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="私聊功能" prop="simpleChat">
                  <el-radio-group v-model="formData.chatInfo.simpleChat">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="消息清理" prop="msgClear">
                  <el-radio-group v-model="formData.chatInfo.msgClear">
                    <el-radio label="1">开启</el-radio>
                    <el-radio label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="清理天数" prop="msgClearDay">
                  <el-input-number v-model="formData.chatInfo.msgClearDay" :min="1" class="w-full" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="撤回时间(秒)" prop="redoTime">
                  <el-input-number v-model="formData.chatInfo.redoTime" :min="60" class="w-full" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发送间隔(秒)" prop="sendInterval">
                  <el-input-number v-model="formData.chatInfo.sendInterval" :min="0" class="w-full" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="STUN服务器" prop="stun">
              <el-input v-model="formData.chatInfo.stun" placeholder="请输入STUN服务器地址" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 文件上传配置 -->
        <el-tab-pane label="文件上传" name="fileUpload">
          <el-form ref="fileUploadFormRef" :model="formData.fileUpload" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="文件大小限制(MB)" prop="size">
                  <el-input-number v-model="formData.fileUpload.size" :min="1" :max="1024" class="w-full" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预览设置" prop="preview">
                  <el-input v-model="formData.fileUpload.preview" placeholder="预览设置" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="允许的文件类型" prop="fileExt">
              <el-select
                v-model="formData.fileUpload.fileExt"
                multiple
                filterable
                allow-create
                placeholder="请选择或输入文件扩展名"
                class="w-full"
              >
                <el-option v-for="ext in commonFileTypes" :key="ext" :label="ext" :value="ext" />
              </el-select>
            </el-form-item>
            <el-alert
              title="提示：可以选择常用文件类型，也可以直接输入自定义扩展名"
              type="info"
              :closable="false"
              show-icon
            />
          </el-form>
        </el-tab-pane>

        <!-- 罗盘配置 -->
        <el-tab-pane label="罗盘配置" name="compass">
          <el-form ref="compassFormRef" :model="formData.compass" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="罗盘状态" prop="status">
                  <el-radio-group v-model="formData.compass.status">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="罗盘模式" prop="mode">
                  <el-radio-group v-model="formData.compass.mode">
                    <el-radio :label="1">模式1</el-radio>
                    <el-radio :label="2">模式2</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="罗盘列表" prop="list">
              <div class="compass-list">
                <el-empty v-if="formData.compass.list.length === 0" description="暂无罗盘配置" />
                <div v-else>
                  <!-- 这里可以根据需要添加罗盘列表的编辑功能 -->
                  <el-text>罗盘列表: {{ formData.compass.list.length }} 项</el-text>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getLookImConfig, updateLookImConfig, resetLookImConfig, type LookImConfigSaveVO } from '@/api/system/lookImConfig'
import { UploadImg } from '@/components/UploadFile'

defineOptions({ name: 'LookImConfig' })

// 响应式变量
const loading = ref(false)
const saveLoading = ref(false)
const resetLoading = ref(false)
const activeTab = ref('sysInfo')

// 表单数据
const formData = reactive<LookImConfigSaveVO>({
  sysInfo: {
    logo: '',
    name: 'look-im',
    state: '1',
    regauth: '0',
    regtype: '2',
    runMode: '1',
    ipregion: '1',
    closeTips: '系统升级维护中，请稍候再试！',
    description: '一款基于vue2.0的即时通信系统',
    registerInterval: '600'
  },
  chatInfo: {
    stun: '',
    online: '1',
    webrtc: '1',
    dbDelMsg: '1',
    msgClear: '1',
    redoTime: '120',
    stunPass: '',
    stunUser: '',
    groupChat: '1',
    simpleChat: '1',
    autoAddUser: {
      status: '0',
      welcome: '你好啊，欢迎来到look-im',
      user_ids: ['1', '2', '3'],
      user_items: ['1', '2', '3']
    },
    msgClearDay: '30',
    autoAddGroup: {
      name: '春游交流',
      status: '0',
      userMax: '100',
      owner_uid: '1',
      owner_info: []
    },
    groupUserMax: '0',
    sendInterval: '0'
  },
  fileUpload: {
    size: '50',
    preview: '',
    fileExt: []
  },
  compass: {
    list: [],
    mode: 1,
    status: 0
  }
})

// 常用文件类型
const commonFileTypes = [
  'jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'webp',
  'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
  'txt', 'md', 'mp3', 'wav', 'mp4', '3gp', 'avi', 'mkv'
]

// 获取配置数据
const getConfigData = async () => {
  try {
    loading.value = true
    const data = await getLookImConfig()
    if (data) {
      // 更新表单数据
      Object.assign(formData.sysInfo, data.sysInfo)
      Object.assign(formData.chatInfo, data.chatInfo)
      Object.assign(formData.fileUpload, data.fileUpload)
      Object.assign(formData.compass, data.compass)
    }
  } catch (error) {
    console.error('获取配置失败:', error)
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

// 保存配置
const handleSave = async () => {
  try {
    saveLoading.value = true
    await updateLookImConfig(formData)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 重置配置
const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置为默认配置吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    resetLoading.value = true
    await resetLookImConfig()
    ElMessage.success('重置成功')
    await getConfigData() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置失败:', error)
      ElMessage.error('重置失败')
    }
  } finally {
    resetLoading.value = false
  }
}

// 刷新配置
const handleRefresh = () => {
  getConfigData()
}

// 组件挂载时获取数据
onMounted(() => {
  getConfigData()
})
</script>

<style lang="scss" scoped>
.compass-list {
  min-height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-logo {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    
    &:hover {
      border-color: #409eff;
    }
  }
  
  :deep(.el-upload-dragger) {
    width: 120px;
    height: 80px;
    border: none;
    border-radius: 8px;
    background: #fafafa;
    
    &:hover {
      background: #f5f7fa;
    }
  }
}
</style>